package com.kee.common.util;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import com.kee.share.bean.Exam;

public class JSoupUtil {
	// Document doc = Jsoup.parse(html);
	
	/**
	 * Document doc = Jsoup.connect("http://www.jb51.net/").get(); String title
	 * = doc.title(); Document doc = Jsoup.connect("http://www.jb51.net")
	 * .data("query", "Java") .userAgent("Mozilla") .cookie("auth", "token")
	 * .timeout(3000) .post();
	 * 
	 * 说明 
	 * Elements这个对象提供了一系列类似于DOM的方法来查找元素，抽取并处理其中的数据。具体如下： 查找元素
	 * getElementById(String id) getElementsByTag(String tag)
	 * getElementsByClass(String className) getElementsByAttribute(String key)
	 * (and related methods) Element siblings: siblingElements(),
	 * firstElementSibling(), lastElementSibling();nextElementSibling(),
	 * previousElementSibling() Graph: parent(), children(), child(int index)
	 * 元素数据 attr(String key)获取属性attr(String key, String value)设置属性
	 * attributes()获取所有属性 id(), className() and classNames()
	 * text()获取文本内容text(String value) 设置文本内容 html()获取元素内HTMLhtml(String
	 * value)设置元素内的HTML内容 outerHtml()获取元素外HTML内容 data()获取数据内容（例如：script和style标签)
	 * tag() and tagName() 操作HTML和文本 append(String html), prepend(String html)
	 * appendText(String text), prependText(String text) appendElement(String
	 * tagName), prependElement(String tagName) html(String value)
	 * @throws IOException 
	 * @throws IOException 
	 */
	
	
	/**
	 * 菁优网选择题
	 */
	public static Exam qingyou(String userAgent,String url) throws Exception{
		Exam exam = new Exam();
		Document doc = Jsoup.connect(url).userAgent(userAgent).timeout(5000).get();
		//详情页
		Element element = doc.getElementsByClass("quesborder").first();
		//特殊数据不爬取
		String elementHTML = element.html();
		if(elementHTML.contains("img") || elementHTML.contains("MathJye")) {
			return null;
		}
		
		
		//题目
		Element timu = element.getElementsByClass("pt1").first();
		Element line = timu.children().first();
		line.remove();
		exam.setExam(timu.html());
		//选项
		Element xuanxiang = element.getElementsByClass("pt2").first();
		Elements x = xuanxiang.select("label");
		StringBuilder sb = new StringBuilder();
		StringBuilder daan = new StringBuilder();
		int i = 64;
		for (Element e : x) {
			//选项
			i++;
			sb.append("[");
			sb.append((char)i);
			sb.append("]");
			sb.append(e.html());
			sb.append("[/");
			sb.append((char)i);
			sb.append("]");
			sb.append("\n");
			//标准答案
			Element t  = e.getElementsByClass("s").first();
			if(t != null){
				daan.append((char)i);
				daan.append(",");
			}
		}
		exam.setOpts(sb.toString());
		exam.setAnswer(daan.toString());
		//考点
		Element kaodian = element.getElementsByClass("pt3").first();
		StringBuilder kaodianStr = new StringBuilder();
		Elements kaodianElements = kaodian.getElementsByTag("a");
		for (Element e : kaodianElements) {
			kaodianStr.append(e.text());
			kaodianStr.append(",");
		}
		exam.setKnowledge(kaodianStr.toString());
		//分析
		Element fenxi = element.select(".pt5").first();
		   //删除em节点
		Elements g = fenxi.children();
		g.remove();
		exam.setAnaly(fenxi.html());
		//解答
		Element jieda = element.getElementsByClass("pt6").first();
		Elements removejieda = jieda.children();
		removejieda.remove();
		exam.setExplains(jieda.html());
		return exam;
	}
	
	/**
	 * 题库网 单选
	 * @param userAgent
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Exam tikudanxun(String userAgent,String url) throws Exception{
		Exam exam =  new Exam();
		Document doc = Jsoup.connect(url).userAgent(userAgent).timeout(5000).get();
		Element element  = doc.getElementsByClass("answer_detail").first();
		//特殊数据不爬取
		String elementHTML = element.html();
		if(elementHTML.contains("img")) {
			return null;
		}
		//标题
		Element title = element.select("dt p").first();
		exam.setExam(title.html());
		//选项
		Elements opts = element.select("dt table td");
		if (opts.size() != 4) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		int i = 64;
		for (Element e : opts) {
			//选项
			i++;
			sb.append("[");
			sb.append((char)i);
			sb.append("]");
			sb.append(e.html());
			sb.append("[/");
			sb.append((char)i);
			sb.append("]");
			sb.append("\n");
		}
		exam.setOpts(sb.toString());
		//标准答案
		Element answer = element.select("dd p i").first();
		exam.setAnswer(answer.text());
		//解析
		Element explain = element.select("dd p").get(1).select("i").first();
		String exlainandknowledge =  explain.html();
		if (!"".equals(exlainandknowledge)) {
			String[] exlainandknowledgeArray = exlainandknowledge.split("考点：");
			exam.setExplains(exlainandknowledgeArray[0].replace("试题分析：", ""));
			// 知识点
			exam.setKnowledge(exlainandknowledgeArray[1]);
		}
		return exam;
	}
	
	/**
	 * 正则解析答案
	 * @param opts
	 * @return
	 */
	public static String regexParseCoocoOpt(String opts) throws Exception{
		StringBuilder sb = new StringBuilder();
		int x = 65;
		for(int i = 1;i<=4;i++){
			//选项
			String c = new String(new char[]{(char)x});
			String nextC = new String(new char[]{(char)(x+1)});
			String reg ;
			if (x == 68) {
				reg = "(" + c + "\\s{0,1}[．\\.])(.+)";
			} else {
				reg = "(" + c + "\\s{0,1}[．\\.])(.+)" + nextC + "\\s{0,1}[．\\.]";
			}
			Pattern pattern = Pattern.compile(reg);
			Matcher m = pattern.matcher(opts);
			while (m.find()) {
				String xuanxiang = m.group(1) + m.group(2);
				sb.append("[");
				sb.append((char)x);
				sb.append("]");
				sb.append(xuanxiang.trim());
				sb.append("[/");
				sb.append((char)x);
				sb.append("]");
				sb.append("\n");
			}
			x++;
		}
		System.out.println(sb.toString());
		return sb.toString();
	}
	
	
	/**
	 * 可圈可点网站选择题
	 * @param userAgent
	 * @param url
	 * @return
	 * @throws Exception 
	 */
	public static Exam coocoxuan(String userAgent,String url) throws Exception{
		Exam exam = new Exam();
		Document doc = Jsoup.connect(url).userAgent(userAgent).timeout(5000).get();
		Element left = doc.getElementById("left");
		Element titleHTML = left.getElementsByClass("txt").first().getElementsByTag("br").first();
		Elements ps = titleHTML.siblingElements();
		StringBuilder sb = new  StringBuilder();
		int i = 1;
		for (Element e : ps) {
			if (i >= 3) {
				String tagName = e.tagName();
				//试题题目
				if (i == 3) {
					System.out.println(e.text());
					i++;
					continue;
				}
				//选择题选项
				if (tagName.equals("p") && !e.text().equals("")) {
					sb.append(e.text().trim());
				} else {
					break;
				}
			}
			i++;
		}
//		System.out.println(sb.toString());
		//解析选项
		String opts = regexParseCoocoOpt(sb.toString());
		//答案解析
		Element daanHTML = doc.getElementsByClass("daan").first();
		//Element daanHTMLP = daanHTML.getElementsByTag("p").get(1);
		
		Element guangaoHTML = daanHTML.getElementsByTag("br").get(1);
		//删除br前面的3个元素
		Node node1 = guangaoHTML.previousSibling();
		node1.remove();
		Node node2 = guangaoHTML.previousSibling();
		node2.remove();
		Node node3 = guangaoHTML.previousSibling();
		node3.remove();
		System.out.println(daanHTML.text());
		return exam;
	}
	
	public static void main(String[] args) throws IOException {
		String userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 SE 2.X MetaSr 1.0";
//		String url ="http://tiku.21cnjy.com/quest/cDMzI__AMj0O.html";
//		try {
//			Exam exam = tikudanxun(userAgent,url);
//			System.out.println("题目:" + exam.getExam());
//			System.out.println("选项:" + exam.getOpts());
//			System.out.println("答案:" + exam.getAnswer());
//			System.out.println("知识点:" + exam.getKnowledge());
//			System.out.println("分析:" + exam.getAnaly());
//			System.out.println("解答:" + exam.getExplains());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		String url = "http://czsw.cooco.net.cn/testdetail/83532/";
		try {
			coocoxuan(userAgent,url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
